from django.shortcuts import render
from rest_framework.viewsets import ModelViewSet
from users.models import User
from rest_framework.response import Response
from rest_framework.decorators import action
from MeiduoExpress.serializer import PlaceOrderSerializer
from MeiduoExpress.models import ExpressInfo
from meiduo_mall.libs.meiduo_express import MeiduoExpress
from rest_framework.permissions import IsAdminUser,IsAuthenticated
from celery_tasks.express.tasks import verify_express

# Create your views here.

class ExpressViewSet(ModelViewSet):

    def get_permission(self):
        if self.action == 'place_order':
            return [IsAdminUser]
        elif self.action == 'prompt_check':
            return [IsAuthenticated]

    @action(methods=['get'], detail=True)
    def get_userinfo(self, request, pk):
        Receiver = User.objects.get(orders__order_id=pk)
        Sender = request.user

        return Response({

            'Receiver': {
                'Name': Receiver.username,
                'Mobile': Receiver.mobile,
                'ProvinceName': Receiver.default_address.province.name,
                'CityName': Receiver.default_address.city.name,
                'ExpAreaName': Receiver.default_address.district.name,
                'Address': Receiver.default_address.place,
            },
            'Sender': {
                'Name': Sender.username,
                'Mobile': Sender.mobile,
                'ProvinceName': Sender.default_address.province.name,
                'CityName': Sender.default_address.city.name,
                'ExpAreaName': Sender.default_address.district.name,
                'Address': Sender.default_address.place,
            }
        })

    @action(methods=['post'], detail=False)
    def place_order(self, request):
        c = request.data['Commodity'] # “手机;电脑”
        request.data['Commodity'] = []
        for temp in c.split(";"):
            request.data['Commodity'].append({
                "GoodsName": temp
            })

        ps = PlaceOrderSerializer(data=request.data)
        ps.is_valid(raise_exception=True)
        # m = MeiduoExpress()
        # result = m.place_order(ps.validated_data)
        #
        # if result['Success']:
        #     ExpressInfo.objects.create(
        #         order_id = result['Order']['OrderCode'],
        #         staff = request.user,
        #         logistic_code = result['Order']['LogisticCode'],
        #         shipper_code = result['Order']['ShipperCode']
        #
        #     )
        #     return Response({'result': True})
        # return Response({'result': False})
        verify_express.delay(ps.validated_data, staff = request.user)
        return Response({'result': True})

    @action(methods=['get'], detail=True)
    def prompt_check(self, request, pk):
        expressinfo = ExpressInfo.objects.get(order_id=pk)
        m = MeiduoExpress()
        result = m.prompt_check(request_data={
            'OrderCode': expressinfo.order_id,
            'ShipperCode': expressinfo.shipper_code,
            'LogisticCode': expressinfo.logistic_code
        })
        return Response(result)

